package com.ruoyi.purchase.service.impl;
import java.util.Date;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.base.domain.Goods;
import com.ruoyi.base.domain.Inventory;
import com.ruoyi.base.domain.SettlementAccount;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.purchase.domain.*;
import com.ruoyi.purchase.dto.PurchaseStoreDto;
import com.ruoyi.purchase.feign.client.GoodsFeignClient;
import com.ruoyi.purchase.mapper.PurchaseOrderDetailMapper;
import com.ruoyi.purchase.mapper.PurchaseOrderMapper;
import com.ruoyi.purchase.mapper.PurchaseReturnPayMapper;
import com.ruoyi.purchase.utils.OrderNoUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.purchase.mapper.PurchaseReturnMapper;
import com.ruoyi.purchase.service.IPurchaseReturnService;

/**
 * 入库Service业务层处理
 *
 * @author wonderland
 * @date 2023-07-18
 */
@Service
public class PurchaseReturnServiceImpl implements IPurchaseReturnService {
    @Autowired
    private PurchaseReturnMapper purchaseReturnMapper;
    @Autowired
    private GoodsFeignClient goodsFeignClient;
    @Autowired
    private PurchaseOrderDetailMapper orderDetailMapper;

    @Autowired
    private PurchaseReturnPayMapper purchaseReturnPayMapper;

    @Autowired
    private PurchaseOrderMapper orderMapper;
    /**
     * 查询入库
     *
     * @param id 入库主键
     * @return 入库
     */
    @Override
    public PurchaseReturn selectPurchaseReturnById(Long id) {
        return purchaseReturnMapper.selectPurchaseReturnById(id);
    }

    /**
     * 查询入库列表
     *
     * @param purchaseReturn 入库
     * @return 入库
     */
    @Override
    public List<PurchaseReturn> selectPurchaseReturnList(PurchaseReturn purchaseReturn) {
        return purchaseReturnMapper.selectPurchaseReturnList(purchaseReturn);
    }

    /**
     * 新增入库
     *
     * @param dto 入库
     * @return 结果
     */
    @Override
    public int insertPurchaseReturn(PurchaseStoreDto dto) {
        // 结算账户回款
        setAccount(dto.getAccountId(), dto.getPayAmount());
        // 减库存
        List<PurchaseOrder> orderList = dto.getOrderList();
        List<Goods> goodsList = getGoodsList(orderList);
        // 保存库存信息
        returnKuCun(goodsList);
        // 保存退款单信息
        PurchaseReturn purchaseReturn = getPurchaseReturn(dto, orderList);
        int i = purchaseReturnMapper.insertPurchaseReturn(purchaseReturn);
        // 保存退款付款单信息
        saveReturnPayInfo(dto, orderList, purchaseReturn);
        // 修改采购单状态为已退单
        updateOrderState(orderList);
        return i;
    }

    private void updateOrderState(List<PurchaseOrder> orderList) {
        orderList.forEach(s ->{
            s.setState(3L);
            orderMapper.updatePurchaseOrder(s);
        });
    }

    private void saveReturnPayInfo(PurchaseStoreDto dto, List<PurchaseOrder> orderList, PurchaseReturn purchaseReturn) {
        orderList.forEach(s ->{
            PurchaseReturnPay purchaseReturnPay = new PurchaseReturnPay();
            purchaseReturnPay.setReturnId(purchaseReturn.getId());
            purchaseReturnPay.setOrderNo(s.getReceiptNumber());
            purchaseReturnPay.setAccountId(dto.getAccountId());
            purchaseReturnPay.setPayAmout(dto.getPayAmount());
            purchaseReturnPayMapper.insertPurchaseReturnPay(purchaseReturnPay);
        });
    }

    private static PurchaseReturn getPurchaseReturn(PurchaseStoreDto dto, List<PurchaseOrder> orderList) {
        PurchaseReturn purchaseReturn = new PurchaseReturn();
        orderList.forEach(order ->{
            purchaseReturn.setBillDate(order.getBillDate());
            purchaseReturn.setSupplierName(order.getSupplierName());
            purchaseReturn.setGoodsInfo(order.getGoodsInfo());
        });
        purchaseReturn.setReceiptNumber(OrderNoUtil.getOrderNo());
        purchaseReturn.setAdminName(dto.getAdminName());
        purchaseReturn.setTotalAmount(dto.getTotalAmount());
        purchaseReturn.setNote(dto.getNote());
        purchaseReturn.setState(dto.getState());
        purchaseReturn.setPayAmount(dto.getPayAmount());
        BigDecimal returnAmount = dto.getTotalAmount().subtract(dto.getDiscountAmount());
        purchaseReturn.setReturnAmount(returnAmount);
        purchaseReturn.setStorageId(dto.getStoreId());
        purchaseReturn.setAccountId(dto.getAccountId());
        return purchaseReturn;
    }

    private void returnKuCun(List<Goods> goodsList) {
        goodsList.forEach(goods -> {
            String code = goods.getCode();
            Long number = goods.getNumber();
            Inventory inventory = goodsFeignClient.getByBarCode(code);// 根据code获取库存信息
            if (inventory != null){
                int returnedQuantity = (int) Math.min(number, inventory.getInventory());
                // 计算退货数量，确保不超过库存数量
                inventory.setInventory(inventory.getInventory() - returnedQuantity);
                // 减少库存数量
                double unitPrice = inventory.getUnitPrice();
                double returnedAmount = unitPrice * returnedQuantity;
                inventory.setInventoryAmount((long) (inventory.getInventoryAmount() - returnedAmount));
                // 更新库存金额
                goodsFeignClient.updateInventory(inventory);
            }
        });
    }

    private List<Goods> getGoodsList(List<PurchaseOrder> orderList) {
        List<Long> orderIds = new ArrayList<>();
        List<Long> goodsIds = new ArrayList<>();
        List<PurchaseOrderDetail> orderDetails = new ArrayList<>();
        List<Goods> goodsList = new ArrayList<>();
        // 遍历订单列表，获取订单的ID并添加到orderIds列表中
        orderList.forEach(o -> {
            Long orderId = o.getId();
            orderIds.add(orderId);
        });
        // 遍历orderIds，根据每个orderId获取对应的购买订单明细记录，并添加到orderDetails列表中
        orderIds.forEach(orderId -> {
            List<PurchaseOrderDetail> orderDetailsByOrderId = orderDetailMapper.getOrderDetailsByOrderId(orderId); // 假设使用orderId查询对应订单明细记录的方法为getOrderDetailsByOrderId()
            orderDetails.addAll(orderDetailsByOrderId);
        });
        orderDetails.forEach(orderDetail -> {
            Long goodsId = orderDetail.getGoodsId();
            goodsIds.add(goodsId);
        });
        goodsIds.forEach(goodId ->{
            Goods goods = goodsFeignClient.getGoodsById(Long.valueOf(goodId));
            goodsList.add(goods);
        });
        return goodsList;
    }

    private void setAccount(Long accountId, BigDecimal payAmount) {
        AjaxResult ajaxResult = goodsFeignClient.getInfo(accountId);
        ObjectMapper objectMapper = new ObjectMapper();
        SettlementAccount account = objectMapper.convertValue(ajaxResult.get("data"), SettlementAccount.class);
        BigDecimal currentBalance = account.getCurrentBalance();
        if (currentBalance != null) {
            BigDecimal newBalance = currentBalance.add(payAmount);
            account.setCurrentBalance(newBalance);
        }
        goodsFeignClient.edit(account);
    }
    /**
     * 修改入库
     *
     * @param purchaseReturn 入库
     * @return 结果
     */
    @Override
    public int updatePurchaseReturn(PurchaseReturn purchaseReturn) {
        return purchaseReturnMapper.updatePurchaseReturn(purchaseReturn);
    }

    /**
     * 批量删除入库
     *
     * @param ids 需要删除的入库主键
     * @return 结果
     */
    @Override
    public int deletePurchaseReturnByIds(Long[] ids) {
        return purchaseReturnMapper.deletePurchaseReturnByIds(ids);
    }

    /**
     * 删除入库信息
     *
     * @param id 入库主键
     * @return 结果
     */
    @Override
    public int deletePurchaseReturnById(Long id) {
        return purchaseReturnMapper.deletePurchaseReturnById(id);
    }
}
